/*******************************************************************************
 * Copyright (c) 2012 Alexandr Tsvetkov.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Alexandr Tsvetkov - initial API and implementation
 * 
 * Project:
 *     TAO Library
 * 
 * File name:
 *     WebDialog.java
 *     
 * License agreement:
 *
 * 1. This code is published AS IS. Author is not responsible for any damage that can be
 *    caused by any application that uses this code.
 * 2. Author does not give a garantee, that this code is error free.
 * 3. This code can be used in NON-COMMERCIAL applications AS IS without any special
 *    permission from author.
 * 4. This code can be modified without any special permission from author IF AND ONLY IF
 *    this license agreement will remain unchanged.
 * 5. SPECIAL PERMISSION for this code usage in COMMERCIAL application SHOULD be obtained
 *    from author.
 ******************************************************************************/
package ua.at.tsvetkov.dialogs.webdialog;

import ua.at.tsvetkov.util.Log;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * @author A.Tsvetkov 2011 http://tsvetkov.at.ua mailto:al@ukr.net
 */
public class WebDialog extends Dialog {

	@SuppressWarnings("deprecation")
	static final FrameLayout.LayoutParams	FILL						= new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
																							ViewGroup.LayoutParams.FILL_PARENT);

	private int										margin					= 4;
	private int										padding					= 2;
	private int										titleColor				= 0xFF6D84B4;
	private float[]								dimensionLandscape	= { 470, 300 };
	private float[]								dimensionPortrait		= { 300, 470 };
	private String									mUrl;
	private WebDialogListener					mListener;
	private ProgressDialog						mSpinner;
	private WebView								mWebView;
	private LinearLayout							mContent;
	private TextView								mTitle;
	private String									title;
	private int										iconId;

	/**
	 * Create the WebDialog - browser page.
	 * 
	 * @param context 
	 * @param url 
	 * @param listener 
	 * @param title
	 * @param titleColor 
	 * @param margin
	 * @param padding
	 * @param dimensionLandscape for example { 470, 300 }
	 * @param dimensionPortrait  for example  { 300, 470 }
	 * @param iconId 
	 */
	public WebDialog(Context context, String url, WebDialogListener listener, String title, int titleColor, int margin, int padding,
			float[] dimensionLandscape, float[] dimensionPortrait, int iconId) {
		super(context);
		mUrl = url;
		mListener = listener;
		this.title = title;
		this.iconId = iconId;
		this.titleColor = titleColor;
		this.margin = margin;
		this.padding = padding;
	}

	/**
	 * Create the WebDialog - browser page.
	 * 
	 * @param context
	 * @param url
	 * @param listener
	 * @param title
	 * @param iconId
	 */
	public WebDialog(Context context, String url, WebDialogListener listener, String title, int iconId) {
		super(context);
		mUrl = url;
		mListener = listener;
		this.title = title;
		this.iconId = iconId;
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Dialog#onStop()
	 */
	@Override
	protected void onStop() {
		Bundle bundle = new Bundle();
		mListener.onComplete(bundle);
		super.onStop();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSpinner = new ProgressDialog(getContext());
		mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mSpinner.setMessage("Loading...");

		mContent = new LinearLayout(getContext());
		mContent.setOrientation(LinearLayout.VERTICAL);
		setUpTitle();
		setUpWebView();
		Display display = getWindow().getWindowManager().getDefaultDisplay();
		final float scale = getContext().getResources().getDisplayMetrics().density;
		@SuppressWarnings("deprecation")
		float[] dimensions = (display.getWidth() < display.getHeight()) ? dimensionPortrait : dimensionLandscape;
		addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f), (int) (dimensions[1] * scale + 0.5f)));
	}

	private void setUpTitle() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		Drawable icon = null;
		try {
			icon = getContext().getResources().getDrawable(iconId);
		} catch (Exception e) {
			Log.w("Can't load image", e);
		}
		mTitle = new TextView(getContext());
		mTitle.setText(title);
		mTitle.setTextColor(Color.WHITE);
		mTitle.setTypeface(Typeface.DEFAULT_BOLD);
		mTitle.setBackgroundColor(titleColor);
		mTitle.setPadding(margin + padding, margin, margin, margin);
		mTitle.setCompoundDrawablePadding(margin + padding);
		mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
		mContent.addView(mTitle);
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void setUpWebView() {
		mWebView = new WebView(getContext());
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.setWebViewClient(new WebDialog.DialogWebViewClient());
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.loadUrl(mUrl);
		mWebView.setLayoutParams(FILL);
		mContent.addView(mWebView);
	}

	private class DialogWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.v("Redirect URL: " + url);
			return false; // true
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			String msg = errorCode + ": " + description + "; " + failingUrl;
			Log.e("Error " + msg);
			mListener.onError(msg);
			WebDialog.this.dismiss();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.v("Webview loading URL: " + url);
			super.onPageStarted(view, url, favicon);
			mSpinner.show();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			String title = mWebView.getTitle();
			Log.v("Page finished URL: " + url);
			if (title != null && title.length() > 0) {
				mTitle.setText(title);
			}
			try {
				mSpinner.dismiss();
			} catch (Exception e) {
			}
		}

	}
}
